package cn.alpha.open.autocode.mavenplugin;

import java.util.List;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.springframework.util.CollectionUtils;

import cn.alpha.open.autocode.convert.ModelConvertor;
import cn.alpha.open.autocode.filter.ModelFilter;
import cn.alpha.open.autocode.generator.FileGenerator;
import cn.alpha.open.autocode.model.TableMeta;
import cn.alpha.open.autocode.source.TableMetaSource;

@Mojo(name = "generate")
public class AutoCodeMojo extends AbstractMojo 
{
	@Parameter
	private AutoCodeConfigure autoCodeCfg;

    @Parameter(defaultValue = "${project}", readonly = true)
    private MavenProject project;

    @Component
    private MavenProjectHelper projectHelper;
	
	@Override
	public void execute() throws MojoExecutionException, MojoFailureException 
	{
		TableMetaSource tableMetaSource=new TableMetaSource(autoCodeCfg.getDataSource());
		tableMetaSource.readTableMeta();
		List<TableMeta> tableMetas=tableMetaSource.getTableMetas();
		
		if(CollectionUtils.isEmpty(tableMetas))
			return;
		
		ModelConvertor convertor=new ModelConvertor(tableMetas, autoCodeCfg.getConvert(),autoCodeCfg.getTemplate());
		convertor.convert();
		
		ModelFilter filter=new ModelFilter(convertor, autoCodeCfg.getFilter());
		filter.filter();
		
		FileGenerator generator=new FileGenerator(convertor,project,autoCodeCfg.isOverride());
		generator.generate();
	}

}
